package com.samsung.controller.lottery;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


//import com.alibaba.fastjson.JSON;
import com.samsung.common.annotation.LoginAjaxAuth;
import com.samsung.common.annotation.LoginAuth;
import com.samsung.common.util.BaseExcelUtil;
import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.Constant;
import com.samsung.dto.lottery.CandidateDto;
import com.samsung.dto.lottery.EventFormDto;
import com.samsung.dto.lottery.ItemDto;
import com.samsung.dto.lottery.ItemResultDto;
import com.samsung.dto.lottery.RecordDto;
import com.samsung.model.common.Page;
import com.samsung.model.lottery.LotteryEvent;
import com.samsung.model.lottery.LotteryItem;
import com.samsung.model.lottery.LotteryRecord;
import com.samsung.model.user.User;
import com.samsung.service.lottery.LotteryService;

/**
 * 
 * @ClassName: LotteryController
 * @Description: TODO(抽奖业务)
 * @date 2015年5月13日下午7:22:09
 * @since 1.0
 */
@Controller
@RequestMapping("/lottery")
public class LotteryController {
	
	@Autowired
	private LotteryService lotteryService;


	/**
	 * 
	 * @Title: lotteryDetailCool 
	 * @Description: TODO(抽奖业务实现炫酷页面) 
	 * @param @return   
	 * @author qin1.li 
	 * @return String    返回类型 
	 * @throws
	 */
	@LoginAuth
	@RequestMapping("/lotteryDetailCool")
	public String LotteryDetailCool() {
		  return "lottery/lotteryDetailCool";
	}
	
	/**
	 * 
	 * @Title: lotteryEvent 
	 * @Description: TODO(抽奖业务实现) 
	 * @param @return   
	 * @author bing1.yuan 
	 * @return String    返回类型 
	 * @throws
	*/
	@LoginAuth
	@RequestMapping("/lotteryEventPage")
	public String lotteryEvent() {
		  return "lottery/lotteryEvent";
	}
	
	/**
    * 
    * @Title: showLottery 
    * @Description: TODO(抽奖前后台交互) 
    * @param @param lotteryEventId
    * @param @return
    * @param @throws Exception    设定文件
    * @author qin1.li 
    * @return ModelAndView    返回类型 
    * @throws
    */
	@LoginAuth
	@RequestMapping("/show")
	public ModelAndView oldShowLottery(String lid ,HttpServletResponse response) throws Exception{
		ModelAndView model = new ModelAndView();
		if(BaseUtil.isEmpty(lid)) {
			throw new Exception("抽奖主题编号不能为空");
		}
		LotteryEvent lotteryEvent = lotteryService.getLotteryEvent(lid);
		if(lotteryEvent == null) {
			throw new Exception("抽奖活动信息不存在，或已被删除");
		}
		List<CandidateDto> candidateList = lotteryService.listByCandidate(lid);
		List<LotteryItem> lotteryItemList = lotteryService.listByItem(lid);
		model.addObject("lotteryEvent",lotteryEvent);
		model.addObject("dataSource", JSONArray.fromObject(candidateList).toString());
		model.addObject("lotteryItem",lotteryItemList);
		
		StringBuffer allClass = new StringBuffer();
		Map<String, Map<String, Object>> keyCodeMap = new HashMap<String, Map<String, Object>>();
		for (LotteryItem item : lotteryItemList) {
			Map<String, Object> codeMap = new HashMap<String, Object>();
			codeMap.put("class", "item_"+item.getOrderNum());
			codeMap.put("name", item.getTitle());
			codeMap.put("itemId", item.getId());
			codeMap.put("total", item.getAmount());
			
			allClass.append("item_"+item.getOrderNum()).append("|");
			keyCodeMap.put(item.getOrderNum()+48+"", codeMap);
		}
		model.addObject("keyCode", JSONArray.fromObject(keyCodeMap).toString());
		if(BaseUtil.isNotEmpty(allClass.toString())) {
			allClass = allClass.deleteCharAt(allClass.lastIndexOf("|"));
		}
		model.addObject("allClass", allClass.toString());
		
		model.setViewName("lottery/lotteryDetailCool");
		return model;
	}
	/**
	 * 
	 * @Title: showLottery 
	 * @Description: TODO(抽奖前后台交互) 
	 * @param @param lotteryEventId
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @author qin1.li 
	 * @return ModelAndView    返回类型 
	 * @throws
	 */
	@LoginAuth
	@RequestMapping("/oldshow")
	public ModelAndView showLottery(String lid ,HttpServletResponse response) throws Exception{
		ModelAndView model = new ModelAndView();
		if(BaseUtil.isEmpty(lid)) {
			throw new Exception("抽奖主题编号不能为空");
		}
		LotteryEvent lotteryEvent = lotteryService.getLotteryEvent(lid);
		if(lotteryEvent == null) {
			throw new Exception("抽奖活动信息不存在，或已被删除");
		}
		List<CandidateDto> candidateList = lotteryService.listByCandidate(lid);
		List<LotteryItem> lotteryItemList = lotteryService.listByItem(lid);
		model.addObject("lotteryEvent",lotteryEvent);
		model.addObject("dataSource", JSONArray.fromObject(candidateList).toString());
		
		List<Map<String, Object>> codeList = new ArrayList<Map<String, Object>>();
		for (LotteryItem item : lotteryItemList) {
			Map<String, Object> codeMap = new HashMap<String, Object>();
			codeMap.put("name", item.getTitle());
			codeMap.put("itemId", item.getId());
			codeMap.put("total", item.getAmount());
			
			codeList.add(codeMap);
		}
		model.addObject("lotteryItem", JSONArray.fromObject(codeList).toString());
		
		model.setViewName("lottery/lotteryDetailCool");
		return model;
	}
  /**
   * 
   * @Title: showLottery 
   * @Description: TODO(这里用一句话描述这个方法的作用) 
   * @param @param lotteryEventId
   * @param @return
   * @param @throws Exception    设定文件 
   * @return ModelAndView    返回类型 
   * @author hd1.zhao
   * @throws
   */
	@LoginAjaxAuth
	@RequestMapping("/lottery")
	public ModelAndView showLotterySingle(String lid) throws Exception{
		ModelAndView mav = new ModelAndView();
		if(BaseUtil.isEmpty(lid)) {
			throw new Exception("抽奖主题编号不能为空");
		}
		LotteryEvent lotteryEvent = lotteryService.getLotteryEvent(lid);
		if(lotteryEvent == null) {
			throw new Exception("抽奖活动信息不存在，或已被删除");
		}
		List<CandidateDto> candidateList = lotteryService.listByCandidate(lid);
		List<LotteryItem> lotteryItemList = lotteryService.listByItem(lid);
		List<String> candidates = new ArrayList<String>();
		for (CandidateDto dto : candidateList) {
			candidates.add(dto.getUid());
		}
		List<ItemDto> itemDtoList = new ArrayList<ItemDto>();
		for (LotteryItem item :lotteryItemList) {
			ItemDto dto = new ItemDto();
			dto.setName(item.getTitle());
			dto.setNum(String.valueOf(item.getAmount()));
			dto.setClas("ipt" + item.getAmount());
			dto.setItemId(item.getId());
			itemDtoList.add(dto);
		}
		mav.addObject("lotteryEvent",lotteryEvent);
		mav.addObject("lotteryCandidate", JSONArray.fromObject(candidates).toString());
		mav.addObject("lotteryItem", JSONArray.fromObject(itemDtoList).toString());
		mav.setViewName("lottery/lotteryDetailSingle");
		return mav;
	}
  /**
   * 
   * @Title: SaveLotteryRecord 
   * @Description: TODO(保存抽奖记录) 
   * @param @param request
   * @param @param response
   * @param @return
   * @param @throws Exception    设定文件
   * @author qin1.li 
   * @return Map<String,Object>    返回类型 
   * @throws
   */
	@LoginAjaxAuth
    @ResponseBody
	@RequestMapping("/saveLotteryRecord")
	public Map<String, Object> saveLotteryRecord(@RequestBody List<RecordDto> recordList) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(recordList==null || recordList.size()<=0) {
			resultMap.put("success", false);
			resultMap.put("msg", "抽奖活动至少需要一条中奖记录");
			return resultMap;
		}
		
		int cnt = lotteryService.getRecordCount(recordList.get(0).getLid());
		if(cnt > 0) {
			resultMap.put("success", false);
			resultMap.put("msg", "本次抽奖活动结果已存在，不能重复保存");
			return resultMap;
		}
		
		for (RecordDto dto : recordList) {
			LotteryRecord rec = new LotteryRecord();
			rec.setId(BaseUtil.getUUID());
			rec.setLid(dto.getLid());
			rec.setIid(dto.getIid());
			rec.setUid(dto.getUid());
			rec.setStartTime(new Date());
			rec.setCreateTime(new Date());
			lotteryService.saveLotteryRecord(rec);
		}
		
		resultMap.put("success", true);
		resultMap.put("msg", "保存成功");
		return resultMap;
    }
	/**
	 * 
	 * @Title: lotteryRecord 
	 * @Description: 抽奖记录展示
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @author pu.huang 
	 * @return Map<String,Object>    返回类型 
	 * @throws
	 */
	@LoginAuth
	@RequestMapping("/result")
	public ModelAndView lotteryRecord(String lid) throws Exception {
		ModelAndView model = new ModelAndView();
		if(BaseUtil.isEmpty(lid)) {
			throw new Exception("抽奖主题编号不能为空");
		}
		LotteryEvent lotteryEvent = lotteryService.getLotteryEvent(lid);
		if(lotteryEvent == null) {
			throw new Exception("抽奖活动信息不存在，或已被删除");
		}
		List<ItemResultDto> resultDtoList = lotteryService.listRecordByEvent(lid);
		
		model.addObject("resultDtoList",resultDtoList);
		model.addObject("lotteryEvent",lotteryEvent);
		model.setViewName("lottery/result");
		return model;
	}
	/**
	 * 
	 * @Title: createLottery
	 * @Description: TODO(新建抽奖并存入数据库中) 
	 * @param @param lotteryEventId
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @author bing1.yuan  
	 * @return Map    返回类型 
	 * @throws
	 */
	@LoginAjaxAuth
	@ResponseBody
	@RequestMapping("/createLottery")
	public Map<String, Object> createLottery(@RequestBody EventFormDto eventFormDto, HttpSession session ){
		Map<String, Object> result = new HashMap<String, Object>();
		//获取登录用户session
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		result=lotteryService.checkLotteryInfo(eventFormDto);
		if(Boolean.parseBoolean(result.get("flag").toString())){
			eventFormDto.setUid(user.getUid());
			int insertResult = lotteryService.insertNewLottery(eventFormDto);
			if(insertResult == 1){
				result.put("flag", true);
				result.put("msg", "保存成功");
				result.put("lid", eventFormDto.getId());
			}
		}
		return result;
	}
	/**
	 * 
	 * @Title: createLottery
	 * @Description: TODO(新建抽奖标题校验) 
	 * @param @param lotteryEventId
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @author bing1.yuan  
	 * @return   Map  返回类型 
	 * @throws
	 */
	@ResponseBody
	@RequestMapping("/checkTitle")
	public Map<String, Object> checkTitle(String title){
		return lotteryService.checkLotteryEvent(title);
	}
	
	@LoginAjaxAuth
	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(String lid, HttpServletRequest req){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		LotteryEvent event = lotteryService.getLotteryEvent(lid);
		if(event == null) {
			resultMap.put("success", false);
			resultMap.put("msg", "抽奖活动不存在");
			return resultMap;
		}
		
		HttpSession session = req.getSession();
		User sessUser = (User) session.getAttribute(Constant.LOGIN_TOKEN);
		if(!sessUser.getUid().equalsIgnoreCase(event.getUid())) {
			resultMap.put("success", false);
			resultMap.put("msg", "您只能删除自己创建的活动");
			return resultMap;
		}
		
		int cnt=lotteryService.delete(lid);
		if(cnt==1){
			resultMap.put("success", true);
			resultMap.put("msg", "删除成功");
		}else{
			resultMap.put("success", false);
			resultMap.put("msg", "删除失败");
		}
		return resultMap;
	}
	
	
	/**
	 * V2 新增
	 * 抽奖列表页面
	 * @return
	 */
	@RequestMapping("lotteryList")
	@LoginAuth
	public ModelAndView voteList(ModelAndView model, HttpServletRequest request,String type) {
		Page page = null;
		
		String pageNow = request.getParameter("pageNow");
		int totalCount = lotteryService.getTotalCount("");
		
		if(pageNow!=null){
			page = new Page(totalCount, Integer.parseInt(pageNow));
		}else{
			page=new Page(totalCount, 1);
		}
		List<LotteryEvent> lotteryInfo = lotteryService.getPageInfo(page.getStartPos(),page.getPageSize());
		model.addObject("page",page);
		model.addObject("lotteryList", lotteryInfo);
		model.setViewName("lottery/lotteryList");
		return model;
	}
	
	
	/**
	 * V2新增
	 * 我参与的抽奖
	 */
	
	@RequestMapping("myJoinlotteryList")
	@LoginAuth
	public ModelAndView toLotteryList(ModelAndView model, HttpServletRequest request) {
		model.setViewName("lottery/myJoinlotteryList");
		return model;
	}
	
	/**
	 * 获取我参与的投票列表数据
	 * @param search_title
	 * @param startDate
	 * @param endDate
	 * @param currentPage
	 * @param session
	 * @return
	 */
	@RequestMapping("myJoinlotteryListData")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, Object> getJoinlotteryList(String searchTitle,String startDate,String endDate,Integer currentPage,HttpSession session){
		Map<String, Object> params =  new HashMap<String, Object>();
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		params.put("uid", user.getUid());
		params.put("searchTitle", searchTitle);
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		Integer totalCount = lotteryService.getLotteryListCount(params);
		Page page = new Page(totalCount, currentPage);
		//测试分页用，每页显示1条
		//page.setPageSize(1);
		params.put("page", page);
		List<Map<String, Object>> result = lotteryService.getLotteryList(params);
		Map<String, Object> reMap = new HashMap<String, Object>();
		reMap.put("result", result);
		reMap.put("page", page);
		return reMap;
	}
	/**
	 * V2新增
	 * 我发起的抽奖 ->页面跳转
	 */
	@RequestMapping("myCreatlotteryList")
	@LoginAuth
	public ModelAndView toMycreateList(ModelAndView model, HttpServletRequest request) {
		model.setViewName("lottery/myCreatlotteryList");
		return model;
	}
	
	/**
	 * 我发起的抽奖查询列表
	 * @param searchTitle
	 * @param startDate
	 * @param endDate
	 * @param currentPage
	 * @param session
	 * @return
	 */
	@RequestMapping("myCreatlotteryListData")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, Object> myCreatlotteryList(String searchTitle,String startDate,String endDate,Integer currentPage,HttpSession session) {
		
		Map<String, Object> params =  new HashMap<String, Object>();
		User user = (User)session.getAttribute(Constant.LOGIN_TOKEN);
		params.put("uid", user.getUid());
		params.put("searchTitle", searchTitle);
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		Integer totalCount = lotteryService.getMyCreateCount(params);
		Page page = new Page(totalCount, currentPage);
		//测试分页用，每页显示1条
		//page.setPageSize(1);
		params.put("page", page);
		List<Map<String, Object>> result = lotteryService.getMyCreatLotteryList(params);
		Map<String, Object> reMap = new HashMap<String, Object>();
		reMap.put("result", result);
		reMap.put("page", page);
		return reMap;
	}
	
	
	/**
	 * 我发起的抽奖导出EXCEL
	 * @param lid
	 * @param request
	 * @return
	 */
	@RequestMapping("/exportExcel")
	@LoginAjaxAuth
	@ResponseBody
	public Map<String, String> exportExcel(String lid,HttpServletRequest request){
		Map<String, String> map = new HashMap<String, String>();
		LotteryEvent lotteryEvent = lotteryService.getLotteryEvent(lid);
		List<ItemResultDto> resultDtoList = lotteryService.listRecordByEvent(lid);
		List<List<Object>> lists = new ArrayList<List<Object>>();
		List<Object> list;
		for(int i=0 ; i<resultDtoList.size() ; i++){
			ItemResultDto dto = resultDtoList.get(i);
			list = new ArrayList<Object>();
			list.add(dto.getLotteryName());
			list.add(dto.getName());
			list.add(dto.getUid());
			list.add(dto.getMobile());
			lists.add(list);
		}
		String title = lotteryEvent.getTitle() + "-抽奖结果";
		String[] rowName = {"奖项","姓名","singleId","手机号"};
		String fileName =  "抽奖结果";
		BaseExcelUtil excelUtil = new BaseExcelUtil(title, rowName, fileName, lists, request);
		try {
			String filePath = excelUtil.export();
			map.put("filePath", filePath);
			map.put("status", "ok");
		} catch (IOException e) {
			map.put("status", "error");
			e.printStackTrace();
		}
		return map;
	}
	
	
}